package com.kun.model;

import java.util.*;

/**
 * 火星
 */
public class Mar {

    /** 火星上的所有好奇号 */
    private Curiosity[][] curiosities;

    /** 记录器 正序记录每个好奇号的最新位置 */
    private TreeMap<Integer,Curiosity> recorder = new TreeMap<Integer,Curiosity>(new Comparator<Integer>() {
        public int compare(Integer obj1, Integer obj2) {
            return obj1.compareTo(obj2);
        }
    });

    public Mar(Curiosity[][] curiosities) {
        this.curiosities = curiosities;
    }

    /**
     * 根据输入命令构造火星环境
     * @param inputCommands
     */
    public Mar(String[] inputCommands) {
        int num = 0;
        Curiosity curiosity = null;
        for (int i = 0; i < inputCommands.length; i++) {
            String command = inputCommands[i];
            if (i == 0){
                int length = Integer.parseInt(command.split(" ")[0]);
                int width = Integer.parseInt(command.split(" ")[1]);
                this.curiosities = new Curiosity[length+1][width+1];
            }else if (i%2 != 0){
                int xPos = Integer.parseInt(command.split(" ")[0]);
                int yPos = Integer.parseInt(command.split(" ")[1]);
                String direction = command.split(" ")[2];
                curiosity = new Curiosity(num++, xPos, yPos, direction);
                if (curiosities[xPos][yPos] != null){
                    throw new RuntimeException("("+xPos+","+yPos+")已被别的火星车占领，请将"+curiosity.getId()+"号火星车投放到其他位置...");
                }
                curiosities[xPos][yPos] = curiosity;
                recorder.put(curiosity.getId(),curiosity);
            }else if (i % 2 == 0){
                curiosity.execCommands(this,command.split(""));
            }
        }
    }

    /**
     * 输出火星上所有的好奇号
     */
    public void drawAllCuriosities(){
        Set<Integer> keySet = recorder.keySet();
        Iterator<Integer> iter = keySet.iterator();
        while (iter.hasNext()) {
            Integer key = iter.next();
            System.out.println(recorder.get(key));
        }
    }

    public Curiosity[][] getCuriosities() {
        return curiosities;
    }

    public TreeMap<Integer, Curiosity> getRecorder() {
        return recorder;
    }
}
